package priv.wjh.study.cloud.feign.api.config;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import priv.wjh.study.cloud.feign.api.JsonUtil;

import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

/**
 * <h1>泛型参数编码</h1>
 *
 * @author wangjunhao
 **/
public class GenericSupportEncoder implements Encoder {

    private static final Set<String> TYPES = new HashSet<>();

    static {
        TYPES.add("T");
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        template.header("Content-Type", "application/json");
        // 参数为泛型
        if (TYPES.contains(bodyType.getTypeName())) {
            // 获取方法上的泛型解析标识
//            GenericResolverAnnotation annotation = ((TypeVariableImpl<?>) bodyType).getGenericDeclaration()
//                    .getDeclaredAnnotation(GenericResolverAnnotation.class);
//            if (annotation != null) {
            // 进行泛型包裹
            GenericWrapper genericWrapper = new GenericWrapper();
            genericWrapper.setClassName(object.getClass()
                                                .getName());
            genericWrapper.setBody(JsonUtil.toJson(object));

            template.body(JsonUtil.toJson(genericWrapper));
            // 添加标识符
            template.header("generic", "true");
            return;
//            }
        }
        template.body(JsonUtil.toJson(object));
    }
}
